﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;

using msword = Microsoft.Office.Interop.Word;

using EnnErrE.BillFiller;

namespace nr.GLV.Windows
{
    partial class CustomersDatagrid
    {
        #region Print Mailing
        private class WorkerArgument
        {
            public bool Preview { get; set; }
            public string FileName { get; set; }
            public string Printer { get; set; }
        }

        private msword.Application word;

        private void PerformMailing()
        {
            MailTemplateChoiceForm frm = new MailTemplateChoiceForm();
            DialogResult result = frm.ShowDialog(this);
            if (result != System.Windows.Forms.DialogResult.Cancel)
            {
                string message = string.Format(
                    "Contribuenti selezionati: {0}." +
                    "\n\rContinuando verrà eseguito in backgroung Microsoft Word per produrre il documento richiesto." +
                    "\n\rContinuare?", dgCustomers.Rows.Count - 1);
                if (MessageBox.Show(message, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        Cursor = Cursors.AppStarting;
                        word = new msword.Application();
                        word.Visible = false;
                        Cursor = Cursors.Default;
                        workerMSWord.RunWorkerAsync(
                            new WorkerArgument()
                            {
                                Preview = result == DialogResult.OK,
                                FileName = frm.TemplateName,
                                Printer = frm.SelectedPrinter
                            });
                    }
                    finally
                    {
                        Cursor = Cursors.Default;
                    }
                }
                else
                    miMessagesMailing.Enabled = true;
            }
            else
                miMessagesMailing.Enabled = true;
        }

        private void WorkInWord(WorkerArgument args)
        {
            try
            {
                msword.Document document = PrepareWordDocument(args.FileName);
                if (args.Preview)
                {
                    PreviewDocument(document);
                }
                else
                {
                    PrintDocument(document, args.Printer);
                    word.Quit(SaveChanges: false);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }

        private void PrintDocument(msword.Document document, string printer)
        {
            string oldPrinter = word.ActivePrinter;
            word.ActivePrinter = printer;
            document.PrintOut(Background: false);
        }

        private void PreviewDocument(msword.Document document)
        {
            word.Visible = true;
        }

        private void PerformReplace(nr.GLV.Data.nrDataSet.CustomersRow row)
        {
            foreach (string placeHolder in PlaceHolders.Keys)
            {
                word.Selection.Find.Forward = false;
                word.Selection.Find.Text = placeHolder;
                string replacement = PlaceHolders[placeHolder];
                switch (replacement[0])
                {
                    case '!':
                        if (replacement.Substring(1).Equals("d"))
                            replacement = DateTime.Now.ToString("d");
                        break;
                    case '>':
                        string[] parts = replacement.Substring(1).Split('|');
                        replacement = row.GetParentRow(parts[0])[parts[1]].ToString();
                        break;
                    default:
                        if (Data.Customers.Columns.Contains(replacement))
                            replacement = row[PlaceHolders[placeHolder]].ToString();
                        break;
                }
                word.Selection.Find.Replacement.Text = replacement;
                word.Selection.Find.Execute(Replace: msword.WdReplace.wdReplaceAll, MatchCase: false, MatchWholeWord: true);
            }
        }

        private msword.Document PrepareWordDocument(string templateName)
        {
            msword.Document template = null;
            msword.Document document = null;
            try
            {
                template = word.Documents.Open(FileName: templateName);
                document = word.Documents.Add();
                foreach (DataGridViewRow row in dgCustomers.Rows)
                    if (row.DataBoundItem != null)
                    {
                        template.Select();
                        word.Selection.WholeStory();
                        word.Selection.Copy();
                        document.Select();
                        word.Selection.WholeStory();
                        word.Selection.EndKey();
                        word.Selection.Paste();
                        word.Selection.EndKey();
                        nr.GLV.Data.nrDataSet.CustomersRow customer =
                            (nr.GLV.Data.nrDataSet.CustomersRow)(row.DataBoundItem as System.Data.DataRowView).Row;
                        PerformReplace(customer);
                        document.Sections.Add(Start: msword.WdSectionStart.wdSectionNewPage);
                    }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
            finally
            {
                if (template != null) template.Close(SaveChanges: false);
            }
            return document;
        }
        #endregion

        #region Print Bills

        private class BillWorkArguments
        {
            public string Company { get; set; }
            public string Motivation { get; set; }
            public string Account { get; set; }
            public string Printer { get; set; }
            public bool Landscape { get; set; }
            public BillSettings Settings { get; set; }
            public BillSettingsForm.BillAlignment Alignment { get; set; }
            public int Counter { get; set; }

            public BillWorkArguments() { Counter = 0; }
        }

        private void PerformBillPrinting()
        {
            BillSettingsForm frm = new BillSettingsForm();
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                workerBills.RunWorkerAsync(
                    new BillWorkArguments()
                    {
                        Motivation = frm.Motivation,
                        Account = frm.AccountNumber,
                        Printer = frm.Printer,
                        Landscape = frm.Landscape,
                        Alignment = frm.Alignment,
                        Settings = frm.Settings,
                        Company = frm.Company
                    });
            }
            else
                miMessagesBills.Enabled = true;
        }

        private BillWorkArguments printArguments;

        private void PrintBills(BillWorkArguments args)
        {
            printArguments = args;

            if (args.Alignment == BillSettingsForm.BillAlignment.Standard)
            {
                bills.DefaultPageSettings.PaperSize = args.Settings.BillSize;
                bills.DefaultPageSettings.Landscape = args.Landscape;
            }

            bills.Print();
        }

        private void bills_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                if (printArguments.Counter < dgCustomers.Rows.Count)
                {
                    DataGridViewRow row = dgCustomers.Rows[printArguments.Counter++];
                    if (row.DataBoundItem != null)
                    {
                        nr.GLV.Data.nrDataSet.CustomersRow customer = ((DataRowView)row.DataBoundItem).Row as nr.GLV.Data.nrDataSet.CustomersRow;
                        BillData data = new BillData()
                        {
                            AccountNumber = printArguments.Account,
                            Address = customer.MainAddress,
                            Amount = customer.PaymentAmount,
                            Author = customer.FullName,
                            City = customer.CitiesRow.FullName,
                            Company = printArguments.Company,
                            Motivation = printArguments.Motivation,
                            ZIP = customer.CitiesRow.ZIP
                        };
                        BillCompiler compiler = new BillCompiler(printArguments.Settings, data);
                        System.Drawing.Image bill = compiler.GetCompiledBill();
                        if (printArguments.Landscape)
                            bill.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                        System.Drawing.Point location = new System.Drawing.Point(0, 0);
                        if (printArguments.Alignment != BillSettingsForm.BillAlignment.Standard)
                            location.X = (bills.PrinterSettings.DefaultPageSettings.PaperSize.Width - bills.PrinterSettings.DefaultPageSettings.PaperSize.Width) / 2;
                        e.Graphics.DrawImage(bill, location);
                    }
                }
                e.HasMorePages = printArguments.Counter < (dgCustomers.Rows.Count - 1);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
            finally
            {
            }
        }
        #endregion
    }
}
